package edu.ncst.baseweb.service.impl.equ;

import cn.wintersun.basecommon.common.Result;
import edu.ncst.baseweb.dao.equ.Equ;
import edu.ncst.baseweb.dao.equ.EquClass;
import edu.ncst.baseweb.mapper.EquClassMapper;
import edu.ncst.baseweb.mapper.EquMapper;
import edu.ncst.baseweb.service.intrer.equ.EquService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class EquServiceImpl implements EquService {
    @Autowired
    private EquMapper equMapper;

    @Autowired
    private EquClassMapper equClassMapper;

    public Result<IPage<Equ>> list(Equ equ){
        QueryWrapper<Equ> queryWrapper = Wrappers.query();
        System.out.println(equ);

        //设备名称查询
        if(StringUtils.isNotEmpty(equ.getName())){
            queryWrapper.like(Equ.COL_NAME,equ.getName());
        }
        if(StringUtils.isNotEmpty(equ.getState())){
            queryWrapper.like(Equ.COL_STATE,equ.getState());
        }
        //查询没有报废的设备
        queryWrapper.eq(Equ.COL_SCRAP, "0");
        //创建页数
        Page<Equ> userPage = new Page<>(equ.getCurrent(), equ.getPageSize());
        Page<Equ> equPage = equMapper.selectPage(userPage, queryWrapper);

        //设备类型id赋值，根据选择的设备类型实现；
        List<Equ> records = equPage.getRecords();
        for (Equ record : records) {
            String className = equClassMapper.findClassNameByClassId(record.getClassId());
            record.setClassName(className);
        }
        return Result.ok(equPage);
    }
    public Result<Object> save(Equ equ){

        //编辑
        if (equ.getId()!=null){
            equMapper.updateById(equ);
        }else {
        //新增
            equ.setScrap(0);
            equMapper.insert(equ);
        }

        return Result.ok();
    }
    @Override
    public Result<List<EquClass>> getClassName() {
        List<EquClass> equClassName = equClassMapper.selectList(null);

        return Result.ok(equClassName);
    }
    //报废
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> delete(String equId) throws Exception {
        //删除之后，借用记录是否保留，能否删除；
        //报废，该表删除一条数据，另外一个表增加一条数据
        if (StringUtils.isBlank(equId)){
            throw new Exception("被报废的id为空");
        }

        List<String> ids = Arrays.stream(equId.split(",")).collect(Collectors.toList());

        List<Equ> equList = equMapper.selectBatchIds(ids);

        for (Equ list : equList) {
            list.setScrap(1);
            list.setScrapTime(new Date());
            QueryWrapper<Equ> queryWrapper = Wrappers.query();
            queryWrapper.in("id",ids);
            equMapper.update(list,queryWrapper);
        }

        QueryWrapper<Equ> queryWrapper = Wrappers.query();
        queryWrapper.in("id",ids);

        return Result.failure(200, "成功！");
    }

    //上传图片
    @Override
    public String uploadFile(MultipartFile file, Integer id){
        try {

            String fileExtension = getFileExtension(Objects.requireNonNull(file.getOriginalFilename()));

            // 定义不同类型的文件扩展名
            List<String> imageExtensions = Arrays.asList("jpg", "jpeg", "png", "gif");
            List<String> videoExtensions = Arrays.asList("mp4", "avi", "mov");
            List<String> pdfExtensions = Collections.singletonList("pdf");


            if (imageExtensions.contains(fileExtension)){
                String basePath = System.getProperty("user.dir");
                String imagePath = basePath + "/files/images/" + file.getOriginalFilename();
                file.transferTo(new File(imagePath));
                equMapper.updateImageById(id,file.getOriginalFilename(),imagePath);

                return "图片上传成功";
            }else if (videoExtensions.contains(fileExtension)){
                String basePath = System.getProperty("user.dir");
                String videoPath = basePath + "/files/videos/" + file.getOriginalFilename();
                file.transferTo(new File(videoPath));
                equMapper.updateVideoById(id,file.getOriginalFilename(),videoPath);

                return "视频上传成功";
            } else if (pdfExtensions.contains(fileExtension)){
                String basePath = System.getProperty("user.dir");
                String filePath = basePath + "/files/files/" + file.getOriginalFilename();
                file.transferTo(new File(filePath));
                equMapper.updateFileById(id,file.getOriginalFilename(),filePath);
                return "文档上传成功";
            }
            return "上传成功";
        } catch (Exception e) {
            return "上传失败: " + e.getMessage();
        }
    }
    //获取文件扩展名
    private String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex >= 0 && dotIndex < fileName.length() - 1) {
            return fileName.substring(dotIndex + 1).toLowerCase();
        }
        return "";
    }
}
